package assignment1.eventplan.request;

import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.util.Log;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.List;

public class Request implements Comparable<Request> {

    private int mSequence;
    private boolean isCancel;
    private long requestId;
    private final String url;
    private List<RequestListener> listeners;

    @Method
    private final int method;

    public Request(String url) {
        this(url, Method.GET);
    }

    public Request(String url, @Method int method) {
        this.url = url;
        this.method = method;
    }

    public void setSequence(int mSequence) {
        this.mSequence = mSequence;
    }

    @Override
    public int compareTo(@NonNull Request another) {
        return mSequence - another.mSequence;
    }

    public void cancel() {
        isCancel = true;
    }

    public long getRequestId() {
        return requestId;
    }

    public void setRequestId(long requestId) {
        this.requestId = requestId;
    }


    public String getUrl() {
        return url;
    }

    public boolean isCancel() {
        return isCancel;
    }

    public String getMethod() {
        switch (method) {
            case Method.GET:
                return "GET";
        }
        throw new IllegalAccessError("unknown http method!");
    }

    public void onResponse(Response response) {
        if (null != listeners) {
            Log.d("request", "onResponse-callback->" + System.currentTimeMillis());
            for (RequestListener listener : listeners) {
                listener.onResponse(this, response);
            }
            Log.d("request", "onResponse-finish->" + System.currentTimeMillis());

        }
    }

    public void addListener(RequestListener listener) {
        List<RequestListener> listeners = this.listeners;
        if (null == listeners) {
            this.listeners = listeners = new ArrayList<>();
        }
        listeners.add(listener);
        Log.d("request", "addListener-add->" + System.currentTimeMillis());

    }

    public int getSequence() {
        return mSequence;
    }

    public interface RequestListener {
        void onResponse(Request request, Response response);
    }


    @IntDef({Method.GET})
    @Retention(RetentionPolicy.SOURCE)
    public @interface Method {
        int GET = 1;
    }
}
